<template>
  <div id="root">
  <div class="todo-container">
    <div class="todo-wrap">
      <MyHeader :addTodo="addTodo"></MyHeader>
      <MyList 
      :todoList="todoList" 
      :checkTodo="checkTodo" 
      :handleTodo="handleTodo"
      ></MyList>
      <MyFooter 
      :todoList="todoList" 
      :clickCheckTodo="clickCheckTodo"
      :dedletDoneTodo="dedletDoneTodo"
      ></MyFooter>
    </div>
  </div>
  </div>
</template>

<script>
import MyHeader from '@/components/MyHeader.vue'
import MyFooter from '@/components/MyFooter.vue'
import MyList from '@/components/MyList.vue'
export default {
  name: 'App',
  data() {
    return {
      // 现在本地存储
      // 写这个[]因为后面footer用到数组的length属性
      todoList:JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  methods:{
    // 添加一个数据
    addTodo(obj){
      this.todoList.unshift(obj)
    },
    // 修改done值,给item组件用（list组件是中间桥梁）
    checkTodo(id){
      this.todoList.forEach(todo=>{
        if(todo.id===id){
          todo.done=!todo.done
        }
      })
    },
    // 根据id删除选项
    handleTodo(id){
      this.todoList=this.todoList.filter(todo=>todo.id!==id)
    },
    // 根据底部改变决定每一项的done值
    clickCheckTodo(val){
      this.todoList.forEach(todo=>{
        todo.done=val
      })
    },
    // 清除已经完成的
    dedletDoneTodo(){
      this.todoList=this.todoList.filter(todo=>!todo.done)
    },
    // 更新失去焦点的数据
    handleBlurTodo(id,value){
      this.todoList.forEach(todo=>{
        if(todo.id===id){
          todo.title=value
        }
      })
    },
  },
  mounted(){
// 处理更新失去焦点之后的数据改变
  this.$bus.$on('updateTodo',this.handleBlurTodo)
  },
  beforeDestroy(){
    // 解绑自定义事件
      this.$$bus.$off('updateTodo')
  },
  // 监视todoList数据改变
  watch:{
    todoList:{
      deep:true,
      handler(newval){
        localStorage.setItem('todos',JSON.stringify(newval))
      }
    }
  },
  components: {
    MyHeader,
    MyList,
    MyFooter,
  }
}
</script>

<style>
/*base*/
body {
  background: #fff;
}
.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}
.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}
.btn-edit{
  color: #fff;
  background-color: skyblue;
  border: 1px solid rgb(93, 136, 153);
  margin-right: 5px;
}
.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}
.btn:focus {
  outline: none;
}
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
